package com.hqyj.freemovie.front.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

public class CopyOnWriteArrayListDemo {

    public static void main(String[] args) throws Exception {

        final List<Integer> list = new ArrayList<Integer>();
        //final List<Integer> list = new CopyOnWriteArrayList<Integer>();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        // 线程A将0-1000添加到list
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);

                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            countDownLatch.countDown();
        }).start();

        // 线程B将1000-2000添加到列表
        new Thread(() -> {
            for (int i = 1000; i < 2000; i++) {
                list.add(i);

                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            countDownLatch.countDown();
        }).start();


        countDownLatch.await();

        System.out.println("list集合的元素个数为：" + list.size());

    }
}
